package com.example;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import org.eclipse.jgit.transport.JschConfigSessionFactory;
import org.eclipse.jgit.transport.OpenSshConfig;
import org.eclipse.jgit.util.FS;

/**
 * Created by Administrator on 2017/2/25.
 */
public class FixedSshSessionFactory extends JschConfigSessionFactory {
    protected String[] identityKeyPaths;

    public FixedSshSessionFactory( String... identityKeyPaths )
    {
        this.identityKeyPaths = identityKeyPaths;
    }

    /* (non-Javadoc)
     * @see org.eclipse.jgit.transport.JschConfigSessionFactory#configure(org.eclipse.jgit.transport.OpenSshConfig.Host, com.jcraft.jsch.Session)
     */
    @Override
    protected void configure(OpenSshConfig.Host hc, Session session )
    {
        // nothing special needed here.
    }

    /* (non-Javadoc)
     * @see org.eclipse.jgit.transport.JschConfigSessionFactory#getJSch(org.eclipse.jgit.transport.OpenSshConfig.Host, org.eclipse.jgit.util.FS)
     */
    @Override
    protected JSch getJSch(OpenSshConfig.Host hc, FS fs ) throws JSchException
    {
        JSch jsch = super.getJSch( hc, fs );
        // Clean out anything 'default' - any encrypted keys
        // that are loaded by default before this will break.
        jsch.removeAllIdentity();
        for( final String identKeyPath : identityKeyPaths )
        {
            jsch.addIdentity( identKeyPath );
        }
        return jsch;
    }
}
